import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/login.vue';
import MainBox from '../views/mainbox.vue';
import RouterConfig from './config'
import { useRouterStore } from '../store/useRouterStore';
import Largescreen from "../views/Largescreen/Largescreen.vue";

export const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
  },
  {
    path: '/mainbox',
    name: 'mainbox',
    component: MainBox,
  },
  {
    path: '/Largescreen',
    name: 'Largescreen',
    component: Largescreen,
  }

];

const router= createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior: () => {
    history.pushState(null, document.URL)
  },
});

router.beforeEach((to, from, next) => {
  const { isGetterRouter } = useRouterStore();
  if (to.path === '/login') {
    next();
  } else {
    if (!localStorage.getItem('token')) {
      next('/login');
    } else {
      if (!isGetterRouter) {
        ConfigRouter();
        next({ path: to.fullPath });
      } else {
        next();
      }
    }
  }
});

const ConfigRouter = () => {
  const { changeRouter } = useRouterStore();
  RouterConfig.forEach(item => {
    router.addRoute('mainbox', item);
  });
  console.log(router.getRoutes());
  router.addRoute('mainbox', {
    path: '/',
    redirect: '/mainbox'
  });
   changeRouter(true) 
};

export default router;